<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1400px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划编号" prop="orderNo">
              <el-input v-model="formData.orderNo" placeholder="请输入计划编号" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据日期" prop="billDate">
              <el-date-picker clearable v-model="formData.billDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择单据日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车间" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer" @select="deptChange" placeholder="选择车间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="formData.businessType" placeholder="请选择业务类型" style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ORDER_BUSINESS_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="formData.orderType" placeholder="请选择订单类型" style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PRODUCTION_ORDER_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库仓库" prop="outWarehouseId">
              <treeselect v-model="formData.outWarehouseId" :options="warehouseTree" :normalizer="normalizerW" @select="onWarehouseChange" placeholder="选择出库仓库" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库库位" prop="outStoreId">
              <el-select v-model="formData.outStoreId" placeholder="请选择出库库位" style="width: 100%">
                <el-option v-for="item in locationList" :key="item.id" :label="item.storageLocationName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库仓库" prop="inWarehouseId">
              <treeselect v-model="formData.inWarehouseId" :options="warehouseTree" :normalizer="normalizerW" @select="onWarehouseInChange" placeholder="选择入库仓库" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库库位" prop="inStoreId">
              <el-select v-model="formData.inStoreId" placeholder="请选择入库库位" style="width: 100%">
                <el-option v-for="item in locationInList" :key="item.id" :label="item.storageLocationName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planBeginTime">
              <el-date-picker clearable v-model="formData.planBeginTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择计划开始时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker clearable v-model="formData.planEndTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择计划结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 物料明细列表 -->
        <el-form-item label="物料清单" prop="materialList">
          <el-table :data="formData.materialList" style="width: 100%" border>
            <el-table-column prop="" label="序号" width="80" type="index" />
            <el-table-column prop="" label="物料名称" width="200">
              <template slot-scope="scope">
                <el-select
                  v-model="formData.materialList[scope.$index].materialId"
                  placeholder="请选择物料"
                  filterable
                  remote
                  :remote-method="(query) => remoteMethod(query, scope.$index)"
                  :loading="itemLoadingMap[scope.$index]"
                  @change="() => handleMaterialSelect(formData.materialList[scope.$index].materialId, scope.$index)"
                >
                  <el-option
                    v-for="item in formData.materialList[scope.$index].materialOptions || []"
                    :key="item.id"
                    :label="item.materialName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="materialCode" label="物料编码"  />
            <el-table-column prop="" label="数量">
              <template slot-scope="scope">
                <el-input
                  v-model.number="formData.materialList[scope.$index].quantity"
                  placeholder="请输入数量"
                  type="number"
                  min="0"
                  step="1"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="" label="批次号">
              <template slot-scope="scope">
                <el-input
                  v-model="formData.materialList[scope.$index].batchNo"
                  placeholder="请输入批次号"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeSupply(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px; text-align: right;">
            <el-button type="primary" icon="el-icon-plus" @click="addSupply">添加物料</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as OrderApi from '@/api/production/order';
  import { listDept } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import * as WarehouseApi from '@/api/storage/warehouse';
  import * as LocationApi from '@/api/storage/location';
  import * as MaterialApi from '@/api/basic/material';

  export default {
    name: "OrderForm",
    components: {
      Treeselect
    },
    data() {
      return {
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
          id: undefined,
          orderNo: undefined,
          billDate: undefined,
          deptId: undefined,
          businessType: undefined,
          deptCode: undefined,
          deptName: undefined,
          planBeginTime: undefined,
          planEndTime: undefined,
          outWarehouseId: undefined,
          outStoreId: undefined,
          inWarehouseId: undefined,
          inStoreId: undefined,
          materialList: []
        },
        // 部门列表
        deptList: [],
        // 仓库树数据
        warehouseTree: [],
        // 出库库位列表
        locationList: [],
        // 入库库位列表
        locationInList: [],
        // 物料加载状态
        materialLoading: false,
        // 存储每个物料项的独立加载状态
        itemLoadingMap: {},
        // 表单校验
        formRules: {
        }
      };
    },
    methods: {
      /** 部门选择变化处理 */
      deptChange(e) {
        this.formData.deptName = e.name;
        this.formData.deptCode = e.deptCode || '';
      },

      /** 部门树数据格式化 */
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children,
          deptCode: node.deptCode
        };
      },

      /** 获取部门列表 */
      async getDeptList() {
        try {
          const response = await listDept();
          this.deptList = this.handleTree(response.data, "id")[0].children;
        } catch (error) {
          console.error('获取部门列表失败', error);
        }
      },

      /** 物料远程搜索方法 - 为特定索引的物料项搜索 */
      async remoteMethod(query, index) {
        // 设置该项的加载状态
        this.$set(this.itemLoadingMap, index, true);
        try {
          const params = {
            pageNo: 1,
            pageSize: 100
          };

          // 如果有查询条件，添加到参数中
          if (query) {
            params.materialName = query;
          }

          const res = await MaterialApi.getMaterialPage(params);
          // 为当前物料项设置独立的物料列表
          if (!this.formData.materialList[index]) {
            this.formData.materialList[index] = {};
          }
          this.$set(this.formData.materialList[index], 'materialOptions', res.data.list);
        } catch (error) {
          console.error('获取物料列表失败:', error);
          // 设置空数组作为默认值
          if (this.formData.materialList[index]) {
            this.$set(this.formData.materialList[index], 'materialOptions', []);
          }
        } finally {
          // 清除加载状态
          this.$set(this.itemLoadingMap, index, false);
        }
      },

      /** 新增：物料选择后处理 */
      async handleMaterialSelect(materialId, index) {
        if (materialId && this.formData.materialList[index] && this.formData.materialList[index].materialOptions) {
          // 从当前项的物料列表中查找选中的物料
          const selectedMaterial = this.formData.materialList[index].materialOptions.find(item => item.id === materialId);
          if (selectedMaterial) {
            // 更新物料相关信息
            this.$set(this.formData.materialList[index], 'materialName', selectedMaterial.materialName);
            this.$set(this.formData.materialList[index], 'materialCode', selectedMaterial.materialNo);
          }
        }
      },

      /** 初始化物料明细的物料信息 */
      async initMaterialDetails() {
        // 为每个物料明细项设置初始物料列表
        for (let i = 0; i < this.formData.materialList.length; i++) {
          const item = this.formData.materialList[i];
          // 为每个物料项创建独立的物料选项数组
          if (!item.materialOptions) {
            this.$set(item, 'materialOptions', []);
          }
        }
      },

      /** 添加物料明细行 */
      addSupply() {
        const newSupply = {
          materialId: undefined,
          materialName: '',
          materialCode: '',
          quantity: null,
          batchNo: '',
          // 为新增项添加独立的物料选项数组
          materialOptions: []
        };
        this.formData.materialList.push(newSupply);

        // 获取索引
        const index = this.formData.materialList.length - 1;
        // 加载默认物料列表
        this.remoteMethod('', index);
      },

      /** 删除物料明细行 */
      removeSupply(index) {
        this.formData.materialList.splice(index, 1);
      },

      /** 获取仓库树数据 */
      async getWarehouseTree() {
        try {
          const params = {
            pageNo: 1,
            pageSize: 1000 // 获取足够多的数据用于构建树
          };
          const res = await WarehouseApi.getWarehousePage(params);
          this.warehouseTree = res.data;
        } catch (error) {
          console.error('获取仓库树数据失败:', error);
          this.$modal.msgError('获取仓库树数据失败');
        }
      },

      /** 树节点标准化处理 */
      normalizerW(node) {
        const result = {
          id: node.id,
          label: node.warehouseName,
          children: undefined
        };
        // 只有当children存在且不为undefined且长度大于0时才添加该字段
        if (node.children && node.children.length > 0) {
          result.children = node.children;
        }
        return result;
      },

      /** 仓库选择变化时触发 */
      async onWarehouseChange(warehouseId) {
        this.formData.outStoreId = null;
        if (warehouseId) {
          await this.getLocationList(warehouseId.id);
        } else {
          this.locationList = [];
        }
      },

      /** 入库仓库选择变化时触发 */
      async onWarehouseInChange(warehouseId) {
        this.formData.inStoreId = null;
        if (warehouseId) {
          await this.getLocationInList(warehouseId.id);
        } else {
          this.locationInList = [];
        }
      },

      /** 根据仓库ID获取出库库位列表 */
      async getLocationList(warehouseId) {
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            warehouseId: warehouseId
          };
          const res = await LocationApi.getLocationPage(params);
          this.locationList = res.data.list;
        } catch (error) {
          console.error('获取库位列表失败:', error);
          this.locationList = [];
        }
      },

      /** 根据仓库ID获取入库库位列表 */
      async getLocationInList(warehouseId) {
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            warehouseId: warehouseId
          };
          const res = await LocationApi.getLocationPage(params);
          this.locationInList = res.data.list;
        } catch (error) {
          console.error('获取库位列表失败:', error);
          this.locationInList = [];
        }
      },

      /** 打开弹窗 */
      async open(id, materialList = null, defaultFormData = null) {
        this.dialogVisible = true;
        this.reset();
        // 加载部门列表和仓库树
        await Promise.all([this.getDeptList(), this.getWarehouseTree()]);
        // 修改时，设置数据
        if (id) {
          this.dialogTitle = "编辑生产订单";
          this.formLoading = true;
          try {
            const res = await OrderApi.getOrder(id);
            this.formData = res.data;

            // 如果有出库仓库ID，获取对应的库位列表
            if (res.data.outWarehouseId) {
              await this.getLocationList(res.data.outWarehouseId);
            }

            // 如果有入库仓库ID，获取对应的库位列表
            if (res.data.inWarehouseId) {
              await this.getLocationInList(res.data.inWarehouseId);
            }

            // 初始化物料明细信息
            await this.initMaterialDetails();
          } finally {
            this.formLoading = false;
          }
        } else {
          this.dialogTitle = "新增生产订单";

          // 设置默认表单数据（如果有）
          if (defaultFormData) {
            // 将默认数据合并到表单中
            Object.assign(this.formData, defaultFormData);
          }

          // 如果传入了物料明细数据，设置到表单中
          if (materialList && materialList.length > 0) {
            this.formData.materialList = materialList;

            // 为每个物料项根据materialName调用remoteMethod
            for (let i = 0; i < this.formData.materialList.length; i++) {
              const item = this.formData.materialList[i];
              if (item.materialName) {
                await this.remoteMethod(item.materialName, i);
              } else {
                // 如果没有物料名称，调用空查询获取默认列表
                await this.remoteMethod('', i);
              }

              // 如果有物料名称，尝试匹配物料ID
              if (item.materialName && item.materialOptions && item.materialOptions.length > 0) {
                const matchedMaterial = item.materialOptions.find(m => m.materialName === item.materialName);
                if (matchedMaterial) {
                  this.$set(this.formData.materialList[i], 'materialId', matchedMaterial.id);
                }
              }
            }
          }
        }
      },
      /** 提交按钮 */
      async submitForm() {
        // 校验主表
        await this.$refs["formRef"].validate();
                  this.formLoading = true;
        try {
          const data = this.formData;
                  // 修改的提交
          if (data.id) {
            await OrderApi.updateOrder(data);
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.$emit('success');
            return;
          }
          // 添加的提交
          await OrderApi.createOrder(data);
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.$emit('success');
        } finally {
          this.formLoading = false;
        }
      },
                      /** 表单重置 */
      reset() {
        this.formData = {
          id: undefined,
          orderNo: undefined,
          billDate: undefined,
          deptId: undefined,
          businessType: undefined,
          deptCode: undefined,
          deptName: undefined,
          planBeginTime: undefined,
          planEndTime: undefined,
          outWarehouseId: undefined,
          outStoreId: undefined,
          inWarehouseId: undefined,
          inStoreId: undefined,
          materialList: []
        };
        this.locationList = [];
        this.locationInList = [];
        this.resetForm("formRef");
      },
      /** 格式化日期为年-月-日格式 */
      formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  };
</script>
